import React, { useState, useRef } from "react";
import ResizeObserver from "rc-resize-observer";
import { Button, Card, Space, Typography, Divider } from "antd";
import "@/tailwind-variables.less";

const { Title, Text } = Typography;

// 主组件
export const RCResizeObserver: React.FC = () => {
  const [boxSize, setBoxSize] = useState({ width: 300, height: 200 });
  const [textAreaSize, setTextAreaSize] = useState({ width: 0, height: 0 });
  const [resizeCount, setResizeCount] = useState(0);
  const [resizeLog, setResizeLog] = useState<string[]>([]);

  const boxRef = useRef<HTMLDivElement>(null);
  const textAreaRef = useRef<HTMLTextAreaElement>(null);

  // 处理尺寸变化
  const handleResize = (
    size: { width: number; height: number },
    element: HTMLElement
  ) => {
    const elementType = element.className.includes("resize-box")
      ? "蓝色框"
      : "文本区域";
    const logEntry = `${new Date().toLocaleTimeString()}: ${elementType} 尺寸变化为 ${Math.round(
      size.width
    )}x${Math.round(size.height)}`;

    setResizeLog((prev) => [logEntry, ...prev.slice(0, 9)]); // 保留最新10条记录
    setResizeCount((prev) => prev + 1);

    if (element.className.includes("resize-box")) {
      setBoxSize(size);
    } else if (element.tagName === "TEXTAREA") {
      setTextAreaSize(size);
    }
  };

  // 改变框大小
  const changeBoxSize = (width: number, height: number) => {
    if (boxRef.current) {
      boxRef.current.style.width = `${width}px`;
      boxRef.current.style.height = `${height}px`;
    }
  };

  // 清空日志
  const clearLog = () => {
    setResizeLog([]);
    setResizeCount(0);
  };

  return (
    <div
      style={{ padding: 24, backgroundColor: "#f5f5f5", minHeight: "100vh" }}
    >
      <Title level={2}>RC Resize Observer 演示</Title>
      <Text type="secondary">
        这个组件演示了如何使用 rc-resize-observer 库来监控元素尺寸变化
      </Text>

      <Divider />

      {/* 控制面板 */}
      <Card title="控制面板" style={{ marginBottom: 16 }}>
        <Space wrap>
          <Button onClick={() => changeBoxSize(200, 150)} type="primary">
            小尺寸 (200x150)
          </Button>
          <Button onClick={() => changeBoxSize(400, 300)}>
            中等尺寸 (400x300)
          </Button>
          <Button onClick={() => changeBoxSize(600, 400)}>
            大尺寸 (600x400)
          </Button>
          <Button onClick={clearLog} danger>
            清空日志
          </Button>
        </Space>
      </Card>

      <div style={{ display: "flex", gap: 16, flexWrap: "wrap" }}>
        {/* 可调整大小的框 */}
        <Card title="可调整大小的元素" style={{ flex: 1, minWidth: 300 }}>
          <ResizeObserver onResize={handleResize}>
            <div
              ref={boxRef}
              className="resize-box"
              style={{
                width: boxSize.width,
                height: boxSize.height,
                backgroundColor: "#1890ff",
                borderRadius: 8,
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                color: "white",
                fontSize: 16,
                fontWeight: "bold",
                transition: "all 0.3s ease",
                cursor: "pointer",
                border: "2px solid #096dd9",
              }}
              title="点击上方按钮改变尺寸"
            >
              {Math.round(boxSize.width)} x {Math.round(boxSize.height)}
            </div>
          </ResizeObserver>

          <div style={{ marginTop: 16 }}>
            <Text strong>当前尺寸：</Text>
            <Text>
              {Math.round(boxSize.width)} x {Math.round(boxSize.height)} 像素
            </Text>
          </div>
        </Card>

        {/* 可调整大小的文本区域 */}
        <Card title="可调整大小的文本区域" style={{ flex: 1, minWidth: 300 }}>
          <ResizeObserver onResize={handleResize}>
            <textarea
              ref={textAreaRef}
              placeholder="拖拽右下角可以调整文本区域大小..."
              style={{
                width: "100%",
                height: 200,
                padding: 12,
                border: "2px solid #d9d9d9",
                borderRadius: 6,
                fontSize: 14,
                lineHeight: 1.5,
                resize: "both",
                outline: "none",
                fontFamily: "monospace",
              }}
              defaultValue="这是一个可以通过拖拽调整大小的文本区域。\n\n尝试拖拽右下角的调整手柄来改变大小，ResizeObserver 会实时监测尺寸变化。\n\n你可以在右侧看到实时的尺寸信息和变化日志。"
            />
          </ResizeObserver>

          <div style={{ marginTop: 16 }}>
            <Text strong>文本区域尺寸：</Text>
            <Text>
              {Math.round(textAreaSize.width)} x{" "}
              {Math.round(textAreaSize.height)} 像素
            </Text>
          </div>
        </Card>

        {/* 信息面板 */}
        <Card title="监听信息" style={{ flex: 1, minWidth: 300 }}>
          <div style={{ marginBottom: 16 }}>
            <Text strong>总调整次数：</Text>
            <Text
              style={{
                color: "#1890ff",
                fontSize: 18,
                fontWeight: "bold",
                marginLeft: 8,
              }}
            >
              {resizeCount}
            </Text>
          </div>

          <Divider style={{ margin: "12px 0" }} />

          <div>
            <Text strong>调整日志：</Text>
            <div
              style={{
                backgroundColor: "#f6f6f6",
                border: "1px solid #d9d9d9",
                borderRadius: 4,
                padding: 12,
                marginTop: 8,
                maxHeight: 300,
                overflowY: "auto",
                fontFamily: "monospace",
                fontSize: 12,
              }}
            >
              {resizeLog.length === 0 ? (
                <Text type="secondary">暂无调整记录</Text>
              ) : (
                resizeLog.map((log, index) => (
                  <div
                    key={index}
                    style={{
                      marginBottom: 4,
                      color: index === 0 ? "#1890ff" : "#666",
                    }}
                  >
                    {log}
                  </div>
                ))
              )}
            </div>
          </div>
        </Card>
      </div>

      {/* 使用说明 */}
      <Card title="使用说明" style={{ marginTop: 16 }}>
        <div style={{ lineHeight: 1.8 }}>
          <Text>
            <strong>rc-resize-observer</strong> 是一个用于监听 DOM
            元素尺寸变化的 React 组件库。主要特点：
          </Text>
          <ul style={{ marginTop: 12, paddingLeft: 20 }}>
            <li>基于浏览器原生的 ResizeObserver API</li>
            <li>支持监听任意 DOM 元素的尺寸变化</li>
            <li>提供准确的宽度和高度信息</li>
            <li>性能优异，不会造成页面重绘</li>
            <li>兼容性好，在不支持 ResizeObserver 的浏览器中会自动降级</li>
          </ul>
          <Text style={{ marginTop: 12, display: "block" }}>
            在这个演示中，你可以：
          </Text>
          <ul style={{ paddingLeft: 20 }}>
            <li>点击控制面板中的按钮来改变蓝色框的尺寸</li>
            <li>拖拽文本区域右下角来手动调整其大小</li>
            <li>观察右侧面板中的实时尺寸信息和变化日志</li>
          </ul>
        </div>
      </Card>
    </div>
  );
};
